package com.my.demo.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.stereotype.Component;

@Component
public class JavaRunPython {
  private String path = System.getProperty("user.dir") + "\\text_rec.py";

  private JavaRunPython() throws FileNotFoundException {
  }

  public String execFunc(String img_path) throws IOException {
    String new_img_path = System.getProperty("user.dir") + img_path;
//    ProcessBuilder pb = new ProcessBuilder("D:\\Anaconda\\Anaconda3\\python.exe", path, new_img_path);
    ProcessBuilder pb = new ProcessBuilder("C:\\ProgramData\\Anaconda3\\python.exe", path, new_img_path);

    Process process = pb.start();

    //接收返回流
    BufferedReader in = new BufferedReader(
            new InputStreamReader(process.getInputStream(), "gbk"));

    //接收错误流
    BufferedReader isError = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), "gbk"));

    StringBuilder sb = new StringBuilder();
    StringBuilder sbError = new StringBuilder();
    String line = null;
    String lineError = null;
    String result = null;

    while ((line = in.readLine()) != null) {
      sb.append(line);
      sb.append("\n");
      result = line;
    }

    while ((lineError = isError.readLine()) != null) {
      sbError.append(lineError);
      sbError.append("\n");

    }

    in.close();
    isError.close();

    return result;
  }
}
